<template>
  <!-- 用户管理 -->
  <div>
    <div>
      <h1>用户管理</h1>
    </div>
    <div class="form-row">
      <div class="form-item">
        <span>状态：</span>
        <el-select v-model="status" placeholder="请选择" style="width: 150px">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>

      <div class="form-item">
        <span>姓名：</span>
        <el-input
          v-model="username"
          placeholder="请输入姓名"
          style="width: 150px"
        ></el-input>
      </div>

      <div class="form-item">
        <span>账号：</span>
        <el-input
          v-model="account"
          placeholder="请输入账号"
          style="width: 150px"
        ></el-input>
      </div>

      <div class="form-item">
        <span>手机号：</span>
        <el-input
          v-model="telephone"
          placeholder="请输入手机号"
          style="width: 150px"
        ></el-input>
      </div>

      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button type="success" @click="handleReset">重置</el-button>
    </div>

    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="username" label="姓名"> </el-table-column>
      <el-table-column prop="account" label="账号"> </el-table-column>
      <el-table-column prop="telephone" label="手机号"> </el-table-column>

      <el-table-column prop="headIcon" label="头像"> 
        <template slot-scope="scope">
          <img v-if="scope.row.headIcon"
            :src="scope.row.headIcon"
           style="width: 80px; height: 80px; border-radius: 50%"
          />
          <img v-else :src="require('@/assets/default.png')" style="width: 80px; height: 80px; border-radius: 50%"/> 
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0" type="success">正常</el-tag>
          <el-tag v-else type="danger">禁用</el-tag>
        </template>
      </el-table-column>

      <!-- 操作列宽度设置为150px -->
      <el-table-column fixed="right" label="操作" width="250">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="ResetUserPassword(scope.row)"
            >重置密码</el-button
          >
          <el-button
            v-if="scope.row.status == 0"
            size="mini"
            type="danger"
            @click="updateUserStatusHandler(scope.row)"
            >禁用</el-button
          >
          <el-button
            v-if="scope.row.status == 1"
            size="mini"
            type="success"
            @click="updateUserStatusHandler(scope.row)"
            >启用</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
  </div>
</template>

<script>
import { selectByCondition, resetPassword, userBlock } from "@/api/user";
export default {
  methods: {
    //重置密码点击事件
    ResetUserPassword(row) {
      this.$confirm(`是否确定重置用户:${row.username}的密码,是否继续？`, {
        confirmButtonText: "确定重置",
        cancelButtonText: "取消",
      })
        .then(() => {
          this.userId = row.userId;
          resetPassword(this.userId).then((response) => {
            if (response.code == 200) {
              this.$message({
                type: "success",
                message: "重置成功",
              });
            }
            this.handleSearch();
          });
        })
        .catch(() => {
          // 取消重置密码的处理逻辑
          this.$message({
            type: "info",
            message: "已取消重置密码",
          });
        });
      console.log(row);
    },

    updateUserStatusHandler(row) {
      this.$confirm(
        `此操作将修改用户名为${row.username}的用户状态, 是否继续?`,
        "温馨提示",
        {
          confirmButtonText: "确定修改",
          cancelButtonText: "取消修改",
        }
      ).then(() => {
        const statusData = {
          userId: row.userId,
          status: row.status === 0 ? 1 : 0,
        };
        userBlock(statusData).then((res) => {
          this.updateDialogVisible = false;
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "修改成功",
            });
            this.handleSearch();
          }
        });
      })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消状态修改"
          });
        });
    },

    //封禁用户点击事件
    BlockUser(row) {
      this.$confirm(`是否确定封禁用户 "${row.username}"？`, "确认封禁", {
        confirmButtonText: "确定封禁",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 用户点击确定
          userBlock(row.userId)
            .then((response) => {
              if (response.code === 200) {
                this.$message.success("用户封禁成功！");
                // 刷新数据
                this.handleSearch();
              } else {
                this.$message.error("封禁失败：" + response.msg);
              }
            })
            .catch((error) => {
              this.$message.error("请求失败：" + error.message);
            });
        })
        .catch(() => {
          // 用户点击取消
          this.$message.info("已取消封禁操作");
        });
    },

    // 查询按钮点击事件
    handleSearch() {
      // 收集查询条件
      const params = {
        status: this.status,
        username: this.username,
        account: this.account,
        telephone: this.telephone,
        currentPage: this.currentPage, //当前页
        pageSize: this.pageSize, //每页大小
      };
      // 调用加载数据方法并传入条件
      this.loadData(params);
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.handleSearch();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handleSearch();
    },

    // 重置按钮点击事件
    handleReset() {
      // 清空所有查询条件
      this.status = "";
      this.username = "";
      this.account = "";
      this.telephone = "";

      // 重置后重新加载全部数据
      this.loadData({});
    },

    // 加载数据方法（接收查询条件参数）
    async loadData(params) {
      try {
        // 调用后端接口并传递查询条件
        const response = await selectByCondition(params);
        // 假设接口返回的数据在response.data中
        this.tableData = response.data.list || [];
        this.total = response.data.total;
      } catch (error) {
        console.error("数据加载失败:", error);
        this.$message.error("加载数据失败，请稍后重试");
      }
    },
  },

  created() {
    // 页面初始化时加载数据（默认无查询条件）
    this.handleSearch();
  },

  data() {
    return {
      userId: null,
      status: "",
      username: "",
      account: "",
      telephone: "",
      currentPage: 1, //当前页
      pageSize: 5, //每页大小
      total: 0,

      // 更新状态选项，启用和禁用
      options: [
        {
          value: 0,
          label: "启用",
        },
        {
          value: 1,
          label: "禁用",
        },
      ],
      tableData: [], // 表格数据
    };
  },
};
</script>


<style scoped>
/* 表单行样式 */
.form-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 20px;
  margin-bottom: 15px;
}

/* 每个表单项的容器 */
.form-item {
  display: flex;
  align-items: center;
}

/* 文本标签样式 */
.form-item span {
  margin-right: 8px;
  white-space: nowrap;
}

/* 分页左对齐样式 */
.pagination-left {
  margin-top: 10px;
  text-align: left;
}
</style>